<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>接口</title>
    <link rel="stylesheet" href="./layui/css/layui.css">
    <style>
        .data-list {
            display: flex;
            flex-direction: column;
            padding: 20px;
        }

        .data-list .data-item {
            display: flex;
            line-height: 30px;
            margin-bottom: 10px;
        }

        .data-list .data-item .data-label {
            width: 80px;
            text-align: right;
            flex-shrink: 0;
        }

        .param-table {
            border-left: 1px solid #eee;
            border-top: 1px solid #eee;
        }

        .param-table th,.param-table td{
            text-align: center;
            min-width: 80px;
            border-right: 1px solid #eee;
            border-bottom: 1px solid #eee;
        }
    </style>
</head>
<body style="padding: 20px 10px;">

<!-- 你的 HTML 代码 -->
<span class="layui-breadcrumb">
  <a href="/index.html">首页</a>
  <a><cite>配置</cite></a>
</span>
<div class="demoTable" style="margin-top: 10px;">
    接口：
    <div class="layui-inline">
        <input class="layui-input" placeholder="搜索接口名称" name="name" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" id="demoReloadBtn">搜索</button>
</div>
<table id="demo" lay-filter="test"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="query">查询</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="stop">停用</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="share">共享</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="view">接口详情</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加接口</button>
    </div>
</script>
<form class="layui-form" lay-filter="formTest" action="" id="addInterface" style="display:none;width: 500px;padding: 20px;">
    <div class="layui-form-item">
        <label class="layui-form-label">接口名称</label>
        <div class="layui-input-block">
            <input id="name" type="text" name="name" placeholder="请输入接口名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">查询语句</label>
        <div class="layui-input-block">
            <textarea id="sql" name="sql" lay-verify="required|sql" placeholder="请输入查询语句" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">参数</label>
        <div class="layui-input-block">
            <textarea id="param" name="param" lay-verify="param" placeholder="请输入查询参数，多个参数逗号隔开" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">共享</label>
        <div class="layui-input-block">
            <input type="radio" name="isShare" value="0" title="否">
            <input type="radio" name="isShare" value="1" title="是" checked>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-danger" lay-submit lay-filter="formDemo">查询</button>
            <button type="button" class="layui-btn" id="saveBtn">确认</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<script src="./layui/layui.js"></script>
<script>
layui.use(['element', 'layer', 'form', 'table', 'jquery'], function(){
  var layer = layui.layer;
  var table = layui.table;
  var form = layui.form;
  var $ = layui.$;

   window.getDataSourceId = function(){
        var url = window.location.href;
        var dataSourceId = parseInt(url.substring(url.lastIndexOf("=") + 1));
        return dataSourceId;
   };

   window.getInterfaceUrl = function(code){
        var url = window.location.href;
        var interfaceUrl = url.substring(0,url.indexOf("interface.html")) + "open-api/getData/"+ code;
        return interfaceUrl;
   };

   window.isBlank = function(str){
    return str == 'undefined' || !str || !/[^\s]/.test(str);
   };

   $("#saveBtn").click(function(){
        var sql = $("#sql").val();
        var name = $("#name").val();
        var isShare = $("input[name='isShare']:checked").val();
        if(name == ""){
            $("#name").addClass("layui-form-danger").focus();
            layer.msg("必填项不能为空", {icon: 5, anim: 6});
            return false;
        }
        if(sql == ""){
            $("#sql").addClass("layui-form-danger").focus();
            layer.msg("必填项不能为空", {icon: 5, anim: 6});
            return false;
        }
        var dataSourceId = getDataSourceId();
        $.ajax({
            type: "POST",
            url: "/interface-info/save",
            data: JSON.stringify({name: name, sql: sql, isShare: isShare, dataSourceId: dataSourceId}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
   });

   form.on('submit(formDemo)', function(data){
    var arr = data.field.param ? data.field.param.split(",") : [];
    $.ajax({
        type: "POST",
        url: "/interface-info/sendTest",
        data: JSON.stringify({"sql":data.field.sql,"param":arr,"datasourceId":getDataSourceId()}),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if(result.code == 0 && result.data){
                layer.msg("查询成功", {icon: 6});
            }else{
                layer.msg("查询失败", {icon: 5});
            }
        }
    });
    return false;
  });

  form.verify({
      sql: function(value, item){ //value：表单的值、item：表单的DOM对象
        if(!value.trim().toLowerCase().startsWith("select")){
          return '请输入正确查询语句';
        }
      }
      ,param: function(value, item){ //value：表单的值、item：表单的DOM对象
        if(value == "" && $("#sql").val().indexOf("?") != -1){
          return '请输入查询参数';
        }
      }
    });

   //第一个实例
  var tableData = [];
  table.render({
    elem: '#demo'
    ,toolbar: '#toolbarDemo'

    ,url: '/interface-info/findPage' //数据接口
    ,method: 'post'
    ,request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
    }
    ,page: true //开启分页
    ,where: {queryModel:{dataSourceId:getDataSourceId()}}
    ,headers: {}
    ,done: function(res, curr, count){
        tableData = res.data;
    }
    ,parseData: function(res){ //res 即为原始返回的数据
        return {
          "code": res.code, //解析接口状态
          "msg": res.msg, //解析提示文本
          "count": res.data.total, //解析数据长度
          "data": res.data.list //解析数据列表
        };
    }
    ,response: {
        statusName: 'code' //规定数据状态的字段名称，默认：code
        ,statusCode: '0000' //规定成功的状态码，默认：0
        ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
        ,countName: 'count' //规定数据总数的字段名称，默认：count
        ,dataName: 'data' //规定数据列表的字段名称，默认：data
    }
    ,contentType: 'application/json'
    ,cols: [[ //表头
      {field: 'id', title: '序号', type: 'numbers', width:80, fixed: 'left'}
      ,{field: 'name', title: '接口名称', edit: 'text'}
      ,{field: 'sql', title: '查询语句', edit: 'text'}
      ,{field: 'isShare', title: '共享', width: 80, templet: function(d){return d.isShare == 1 ? "是" : "否";}}
      ,{field: 'status', title: '状态', width: 80, templet: function(d){return d.status == 1 ? "正常" : "停用";}}
      ,{fixed: 'right', title: '操作', width:300, align:'center', toolbar: '#barDemo'}
    ]]
  });

  //触发事件
    table.on('toolbar(test)', function(obj){
      switch(obj.event){
        case 'add':
            layer.open({
              type: 1,
              title: '添加查询接口',
              area: '600px',
              content: $('#addInterface') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        break;
      };
    });

    table.on('edit(test)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
      if(obj.field == "sql" && !obj.value.trim().toLowerCase().startsWith("select")){
        layer.alert('请输入正确查询语句');
        return false;
      }
      if(obj.field == "param" && obj.value == "" && obj.data.sql.indexOf("?") != -1){
        layer.alert('请输入查询参数');
        return false;
      }
      $.ajax({
        type: "POST",
        url: "/interface-info/save",
        data: JSON.stringify(obj.data),
        contentType: 'application/json',
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                layer.msg('保存成功', {icon: 6})
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
      });
    });

    //工具条事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data; //获得当前行数据
      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

      if(layEvent === 'query'){ //执行
        //do somehing
        window.location.href = '/execute.html?interfaceId=' + data.id;
      } else if(layEvent === 'del'){ //删除
        if(!data.id){
            obj.del();
            return false;
        }
        layer.confirm('确认删除接口吗？', function(index){
          layer.close(index);
          //向服务端发送删除指令
          $.ajax({
            type: "POST",
            url: "/interface-info/deleteById",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('删除成功', {icon: 6})
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
          });
        });
      } else if(layEvent === 'stop'){ //停用
        layer.confirm('确认'+ (data.status == 1?"停用":"启用") +'接口吗？', function(index){
          layer.close(index);
          //向服务端发送删除指令
          $.ajax({
            type: "POST",
            url: "/interface-info/stop",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
          });
        });
      } else if(layEvent === 'share'){ //共享
        $.ajax({
            type: "POST",
            url: "/interface-info/share",
            data: JSON.stringify({"id":data.id}),
            contentType: 'application/json',
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
          });
      } else if(layEvent === 'view'){ // 详情
        if(!data.id){
            return false;
        }
        var html = '';
        html += '<div class="data-list">';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">接口名称：</div>';
        html += '        <div class="data-block">'+ data.name +'</div>';
        html += '    </div>';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">接口地址：</div>';
        html += '        <div class="data-block">'+ getInterfaceUrl(data.code) +'</div>';
        html += '    </div>';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">请求方法：</div>';
        html += '        <div class="data-block">POST</div>';
        html += '    </div>';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">是否共享：</div>';
        html += '        <div class="data-block">' + (data.isShare == 1 ? '是' : '否') + '</div>';
        html += '    </div>';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">请求参数：</div>';
        html += '        <div class="data-block">';
        html += '           <table class="param-table">';
        html += '               <tr><th>名称</th><th>必填</th><th>类型</th><th>位置</th><th>说明</th></tr>';
        html += '               <tr><td>key</td><td>' + (data.isShare == 1?"否":"是") + '</td><td>String</td><td>query</td><td>请求key</td></tr>';
        html += '               <tr><td>param</td><td>' + (data.sql.indexOf("?")!=-1?"是":"否") + '</td><td>Object[]</td><td>query</td><td>查询参数</td></tr>';
        html += '           </table>';
        html += '       </div>';
        html += '    </div>';
        html += '    <div class="data-item">';
        html += '        <div class="data-label">调用次数：</div>';
        html += '        <div class="data-block">'+ (data.count ? data.count : 0) +' 次</div>';
        html += '    </div>';
        html += '</div>';
        layer.open({
            type: 1,
            title: "接口详情",
            area: '600px',
            content: html
        });
      } else if(layEvent === 'LAYTABLE_TIPS'){
        layer.alert('Hi，头部工具栏扩展的右侧图标。');
      }
    });

    $("#demoReloadBtn").click(function(){
        var name = $("#demoReload").val();
        table.reload('demo', {where: {queryModel: {name: name}}}, true);
      });
});
</script>
</body>
</html>